﻿<%@ Page Title="" Language="C#" MasterPageFile="~/master/m.master" %>

<script runat="server">

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link href="../assets/css/plugins/jsTree/style.min.css" rel="stylesheet" />
    <link href="../assets/css/plugins/iCheck/customsmall.css" rel="stylesheet" />
    <link href="../assets/css/plugins/bootstrap-select/bootstrap-select.min.css" rel="stylesheet" />
    <style>
        .system-box .right-side{width: 100%;}
        .system-box .right-content-box{overflow: hidden;}
        .mainContent { height: 100%;background-color: #ffffff; min-width: 650px; }
        .mainContent .part{height: 100%; display: inline-block; background-color: #ffffff; vertical-align: top; border: 1px solid #dddddd;}
        .mainContent .part .title{border-bottom: 1px solid #dddddd; height: 30px; line-height: 30px; padding-left: 5px;    background-color: #eee;}
        .leftPart { width: 350px; max-width: 500px;/*overflow: auto;*/}
        .shopPart{ width: calc(100% - 355px); min-width: 320px;/*overflow: auto;*/}


        .leftPart .titleText { height: 30px; line-height: 30px; display: inline-block;  }
        .shopPart .titleText { height: 30px; line-height: 30px; display: inline-block;  }


        .leftPart .searchbox{width: 140px; display: inline-block; float: right;}
        .shopPart .searchbox{width: 180px; display: inline-block; float: right;}


        .btn-filter-users { -ms-border-radius: 0px; border-radius: 0px; }

        #shopDataList tr.check, .table-select tbody tr.check td:first-child {border-left: 4px solid #7acf89;}
        #shopDataList tr.check td, .table-select tbody tr.check td {background: #dff0d8;color: #222121;}

        .wxBox { position: absolute; right: 2px; top: 2px; display: inline-block; }
        .wxBox .dropdown-toggle { padding-top: 3px !important; padding-bottom: 3px !important; }
        .wxTitle { display: inline-block; position: relative; top: 2px; }
        .wxSelect { display: inline-block; min-width:310px; }

        .currentUser{ color: #eb2f2e; margin-left: 2px;}

        .right-content-box {overflow: hidden !important;}
        #groupdata{overflow: auto;height: calc(100% - 30px);}
        #shopList{overflow: auto;height: calc(100% - 30px);}

        .tbTitle{ background-color: #eeeeee;}
        .tbTitle{ background-color: rgba(238, 238, 238, 0.5);}
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="main" runat="Server">
    <div class="system-box">
        <div class="right-side">
            <div class="btns-container"></div>
            <div class="right-content-box">
                <%--<div class="header-tips">企业微信用户报表授权</div>--%>
                <div class="mainContent">
                    <div class="wxBox">
                        <div class="wxTitle">企业微信：</div>
                        <div class="wxSelect">
                            <select id="wxWorkSelectList" class="selectpicker" title="选择消息类型" data-style="dropdownColor" data-width="100%">
                            </select>
                        </div>
                    </div>
                    <div class="leftPart part">
                        <div class="title">
                            <div  class="titleText">
                                部门用户列表
                            </div>
                            <div class="searchbox">
                                <div class="input-group">
                                    <input type="text" class="form-control input-sm filter-users" id="searchUser"  placeholder="查找用户">
                                    <span class="input-group-btn">
                                        <button class="btn btn-primary btn-filter-users btn-sm" type="button">查找</button>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div id="groupdata"></div>
                    </div>
                     

                    <div class="shopPart part">
                        <div class="title">
                            <div  class="titleText">
                                店铺列表 <span class="currentUser"></span>
                            </div>
                            <div class="searchbox">
                                <div class="input-group">
                                    <input type="text" class="form-control input-sm filter-users" placeholder="查找店铺名称">
                                    <span class="input-group-btn">
                                        <button class="btn btn-primary btn-filter-users btn-sm" type="button">查找</button>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div id="shopList">
                            <table class="footable table table-stripped table-list">
                                <thead>
                                <tr class="tbTitle">
                                    <th style="width: 40px;"><input type="checkbox" id="shopListcheckAllShop" /></th>
                                    <th style="width: 40px;">店铺编码</th>
                                    <th style="width: 140px;">店铺名称</th>
                                </tr>
                                </thead>
                                <tbody id="shopDataList"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="footer" runat="Server">
    <script src="../assets/js/plugins/iCheck/icheck.min.js"></script>
    <script src="../assets/js/plugins/iCheck/icheckAll.js"></script>
    <script src="../assets/js/page/rScroll.js"></script>
    <script src="../assets/js/page/pageControl.js"></script>
    <%--<script src="../assets/js/page/tableControl.js"></script>--%>
    <script src="../assets/js/plugins/jsTree/jstree.min.js"></script>
    <script src="../assets/js/plugins/bootstrap-select/bootstrap-select.min.js"></script>
    <script src="../assets/js/plugins/bootstrap-select/i18n/defaults-zh_CN.min.js"></script>
    
    <script type="text/html" id="tpl-shop-list">
    {{# for(var i = 0, len = d.length; i < len; i++){ }}
    <tr {{# if(i%2 == 0){ }} class="gradeX footable-even"
        {{# }else{ }} class="gradeX footable-odd" {{# } }}>
        <td><input type="checkbox"  class="checkPlan shop_{{d[i].ShopCode}}"   data-index="{{i}}" /></td>
        <td class="ShopCode">{{d[i].ShopCode}}</td>
        <td class="ShopName">{{d[i].ShopName}}</td>
    </tr>
    {{# } }}
</script>
    <script>
        //搜索过滤之后的列表没法知道原始的数据的总条数，影响了全选的判断，在这里记录店铺列表的原始记录总数
        //每次读取店铺列表的时候都会更新一次
        var CurrentShopList = null;
        var CurrentUserId = "";

        $(document).ready(function () {
            //绑定下拉框
            var bindWxCorpInfoList = function (controller, action, params, els, size, callback) {
                Y.API2(controller, action, params, function (data) {
                    if (data.Success == false) {
                        swal(data.Message, '', 'error');
                    } else {
                        var html = '';
                        data.map(function (item) {
                            html += '<option value=' + item.CIdentification + '>' + (item.CorpName + '-' + item.AgentName) + '</option>';
                        });
                        els.map(function (item) {
                            $(item).html("");
                            $(item).html(html);
                            $(item).selectpicker({
                                size: size,
                                'title': '请选择'
                            });
                            $(item).selectpicker('refresh');
                        });
                        if (typeof callback === "function") {
                            callback();
                        }
                    }
                });
            }
            //绑定数据到企业微信下拉框
            var loadWxCorpInfoList = function (els, callback) {
                bindWxCorpInfoList('WxCorpInfo', 'GetWxCorpInfoList', {}, els, 6, callback);
            }

            //模块ID
            var ModuleID = Y.getUrlParam("ModuleID");

            //获取按钮
            commonUtil.loadBtnList(ModuleID, function () {
                rScroll();
            });

            //自动高 DOCUMENT高减按钮栏+其它
            //$(".chooseArea .leftArea1").height($(document).height() - (35 + 145));

            //根据IsChecked跟ShopCode的二次排序算法(自己写的，应该木有bug?)
            var mySort = function (a, b) {
                if (a.IsChecked === b.IsChecked) {
                    var val1 = a.ShopCode;
                    var val2 = b.ShopCode;
                    if (val1 < val2) {
                        return -1;
                    } else if (val1 > val2) {
                        return 1;
                    } else {
                        return 0;
                    }
                } else {
                    return b.IsChecked - a.IsChecked;
                }
            }


            var getDateTimeNow = function () {
                var date = new Date();
                var seperator1 = "-";
                var seperator2 = ":";
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                    + " " + date.getHours() + seperator2 + date.getMinutes()
                    + seperator2 + date.getSeconds();
                return currentdate;
            };

            var bindShopTable = function (dataList) {
                console.log(getDateTimeNow());

                var pl = document.getElementById('tpl-shop-list').innerHTML;
                laytpl(pl).render(dataList, function (html) {
                    document.getElementById('shopDataList').innerHTML = html;
                    $(".shopPart .footable").icheckAll({
                        checkObj: "#shopDataList .checkPlan", //表格下面的选择控件对象 选择器
                        checkAllObj: "#shopListcheckAllShop", //全选 选择器
                        clickoutBoxCheck: false, //点击行 不选中
                        checkboxMargin: "4px 0 0 0 " //上右下左
                    });


                    for (var i = 0; i < dataList.length; i++) {
                        if (dataList[i].IsChecked == true) {
                            $("#shopDataList .shop_" + dataList[i].ShopCode).iCheck('check');
                        }
                    }
                });
            };

            var getShopListByUserId = function () {
                var name = $('.shopPart .filter-users').val().trim().replace(/'/g, '');
                Y.API2('WxReport', "GetShopListByUserId", { ShopName: name, UserId: CurrentUserId }, function (data) {
                    if (data.Success == false) {
                        swal(data.Message, '', 'error');
                    } else {
                        console.log("shoplist", data);
                        $("#shopDataList .checkPlan").iCheck('uncheck');
                        if (data.length == 1 && data[0].QueryFlag == 1) {
                            $("#shopDataList .checkPlan").iCheck('check');
                        } else {
                            bindShopTable(data);
                        }
                    }
                });
            };
 

            //获取部门用户tree列表
            var loadDepartmentList = function (wxWorkId) {
                Y.API2('WxUser', 'GetDepartmentList', { wxConfig: wxWorkId}, function (json) {
                    if (json.Success === false) {
                        swal(json.Message, '', 'error');
                    } else {
                        var newdata = $.map(json, function (obj) {
                            obj.parent = obj.parentid == "0" ? "#" : obj.parentid;
                            obj.state = { opened: (obj.parentid === 1) || obj.id === 1 };
                            obj.li_attr = { id: obj.id, userId: obj.UserId, departmentId: obj.DepartmentId,UserName:obj.name };
                            obj.type = (obj.UserId === "" ? "default" : "child");
                            obj.text = obj.name;
                            return obj;
                        });

                        //数据组列表
                        $('#groupdata').jstree({
                            'core': { data: newdata },
                            "checkbox": { "keep_selected_style": false },
                            "search": {
                                show_only_matches: true
                            },
                            "types": {
                                "default": { "icon": "fa fa-folder text-info" },
                                "child": { "icon": "fa fa-user" }
                            },
                            "plugins": ["checkbox", "types", "search"]
                        }).on("ready.jstree", function () {
                            console.log("ready.初始化完毕");
                            layer.closeAll('dialog');

                        }).on("changed.jstree", function (e, data) {
                            //console.log("id=" + data.node.li_attr.id, "uid=" + data.node.li_attr.userId, "departmentId"+data.node.li_attr.departmentId);
                            if (data.action == "deselect_node") {
                                CurrentUserId = "";
                                $('.currentUser').text("");
                                //取消选择的时候不勾选右边列表
                                $("#shopDataList .checkPlan").iCheck('uncheck');
                                return false;
                            }

                            var userId = data.node.li_attr.userId || "";
                            var userName = data.node.li_attr.UserName || "";
                            if (userId !== "") {
                                CurrentUserId = userId;
                                $('.currentUser').text(" -- 当前用户：" + userName + "(" + userId + ")");
                                $('.shopPart .filter-users').val("");
                                getShopListByUserId();
                            }

                            //debugger
                        });

                    }
                    // console.log(data)
                });
            }





            //获取店铺列表
            var loadShopList = function (wxWorkId) {
                CurrentShopList = null;
                var title = $('.shopPart .filter-users').val().trim().replace(/'/g, '');
                pageControl.init('WxReport', 'GetShopList', {
                    shopTitle: title,
                    needLayer: true,
                    alwaysCallBack: function () {
                        $('#shopDataList').empty();
                    }
                }, function (result) {
                    var tBody = [];
                    if (!Y.checkNull(result)) {
                        if (result.data.length == 0) {
                            Y.NoData(tBody, 5);
                            return false;
                        }
                        CurrentShopList = result.data;
                        //绑定店铺数据
                        bindShopTable(CurrentShopList);
                        rScroll();
                    }
                });
            }



            //过虑
            $(".shopPart .btn-filter-users").on("click", function () {
                if (CurrentUserId == "") {
                    loadShopList();
                } else {
                    getShopListByUserId();
                }
            });

            $(".leftPart .btn-filter-users").on("click", function () {
                var v = $('#searchUser').val();
                $('#groupdata').jstree(true).search(v);
            });


            //选中记录
            $('#shopDataList').on('click', 'tr', function () {
                $('#shopDataList tr').removeClass('check');
                $(this).addClass('check');
            });


            //提交
            $(document).on("click", "#btn-save", function () {
                var userIdList = [];
                var selectedNodeIdArr = $('#groupdata').jstree("get_bottom_selected");
                for (var i = 0; i < selectedNodeIdArr.length; i++) {
                    var id = selectedNodeIdArr[i];
                    var node = $('#groupdata').jstree("get_node", id);
                    if (node.li_attr.userId !== "") {
                        var userId = node.li_attr.userId;
                        var userData = {
                            userId: node.li_attr.userId,
                            userName:node.li_attr.UserName
                        }
                        userIdList.push(userData);
                    }
                }

                if (userIdList.length === 0) {
                    swal("请选择要操作的用户", '', 'error');
                    return false;
                }

                //先拿到所有勾选的店铺
                var shopList = [];
                $('#shopDataList .checkPlan:checked').parents('tr').each(function(index, element) {
                    var code = $(element).find('.ShopCode').text();
                    var name = $(element).find('.ShopName').text();
                    shopList.push({ ShopCode: code, ShopName: name });
                });

                var queryFlag = 2;
                //如果勾线的数量跟数据源总数 一样就是全选了
                if (shopList.length === CurrentShopList.length) {
                    queryFlag = 1;
                }

                console.log(userIdList);

                var model = {
                    QueryFlag: queryFlag,
                    MemberIdList: userIdList,
                    ShopList: shopList
                }

                console.log(model);

                Y.API2('WxReport', 'SetMemberShopRelation', model, function (data) {
                    if (data.Success == false) {
                        swal(data.Message, '', 'error');
                    } else {
                        swal("保存成功", '', 'success');
                        getShopListByUserId();
                    }
                });


            });





            //部门-用户模糊搜索
            $('.leftPart .filter-users').keypress(function (event) {
                if (event.which == 13) {
                    var v = $('#searchUser').val();
                    $('#groupdata').jstree(true).search(v);
                }
            });



            //店铺-用户模糊搜索
            $('.shopPart .filter-users').keypress(function(event) {
                if (event.which == 13) {
                    if (CurrentUserId == "") {
                        loadShopList();
                    } else {
                        getShopListByUserId();
                    }
                }
            });


            $('#wxWorkSelectList').on('changed.bs.select', function (e) {
                var wxWorkId = $('#wxWorkSelectList').selectpicker('val');
                console.log(wxWorkId);
                //layer.msg('玩命加载中……', { icon: 16, shade: 0.01, time: 0, maxWidth: 200 });
                $('#groupdata').jstree("destroy");

                loadDepartmentList(wxWorkId);
                loadShopList();
            });

            loadWxCorpInfoList(["#wxWorkSelectList"]);

        })
    </script>
</asp:Content>

